/*
 * Field.scala
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.squela
package sql

trait SqlField[T] extends org.squela.Field[T] {
  type ResourceType = Table
  private[this] var _resource: Table = null
  override def resource = _resource
  def resource_=(table: Table) {cachedReference = null; _resource = table}

  var extraColumnDefinition = ""

  /**
   * As this field might be a reference in a Table, that fact is specified by the return beign an Option.
   * Tipically, this method is called when inheritting the primarykey of another table, when that happens
   * the buildPrimaryKey adds the field from the other table as a reference, but the val defined in the primarykey
   * remains a SqlField, thats why, this method is convenient to retrieve the associated Reference
   */
  private[this] var cachedReference: Option[Table.ReferenceField[T]] = null
  def reference: Option[Table.ReferenceField[T]] = {
    if(cachedReference == null) {
      if(resource == null) cachedReference = None
      else cachedReference = resource.references.find(_.field eq this).asInstanceOf[Option[Table.ReferenceField[T]]]
      return cachedReference
    } else return cachedReference
  }
}
class Field[T: Manifest](val name: String, val length: Int = 0, val unique: Boolean = false, val optional: Boolean = false) extends SqlField[T]{

  val fieldType = manifest[T].erasure.asInstanceOf[Class[T]]

//    def this(name: String)(implicit manifest: scala.reflect.Manifest[T]) = this(name, 0, false, true)
//    def this(name: String, length: Int)(implicit manifest: scala.reflect.Manifest[T]) = this(name, length, false, true)
}
